package com.bos.realm;

import com.bos.dao.IFuntionDao;
import com.bos.dao.IUserDao;
import com.bos.domain.Function;
import com.bos.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import sun.dc.pr.PRError;

import java.security.SecureRandom;
import java.util.Collections;
import java.util.List;

/**
 * @author Administrator
 * 授权和认证领域
 */
public class BosRealm extends AuthorizingRealm {

    @Autowired
    public IUserDao userDao;

    @Autowired
    private IFuntionDao funtionDao;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        //获得页面输入的用户名
        String username = usernamePasswordToken.getUsername();

        //根据用户名来查询用户,因此需要注意用户名要唯一
        User user = userDao.finByUserName(username);
        if (user == null){
            //用户名不存在
            return null;
        }
        //简单认证信息，shiro框架负责比对该用户数据库中的密码和用户登录页面输入的密码是否一致
        AuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
        return info;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /*为当前用户授予权限信息*/
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        /*授予当前用户相应权限,先从数据库查询当前用户的权限*/
        //TODO 查询当前用户的权限信息进行授权
        //获得当前用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //判断是否是超级管理员

        List<Function> functions = null;
        if (user.getUsername().equals("admin")) {
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Function.class);
             functions = funtionDao.findByCriteria(detachedCriteria);
        }else {
            //查询其他用户对应的权限
            functions = funtionDao.findByFuntionByUserId(user.getId());
        }
        //授予该用户权限，以权限关键字的形式识别
        for (Function function : functions) {
            authorizationInfo.addStringPermission(function.getCode());
        }
        return authorizationInfo;
    }
}
